#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
        ui->setupUi(this);
        count = 0;
        countPlay  = 0;
        current_path = QDir::currentPath();
        current_path += "/test_rawdata.wav";
        qDebug() << "Current path/ test file is " << current_path;
        ui->statusBar->showMessage("Click Record button to record the voice");
        file = NULL;
}

MainWindow::~MainWindow()
{
        delete ui;
}

#if USE_SAMPLE_16000
	#define SAMPLE_RATE 16000
#else
	#define SAMPLE_RATE 8000
#endif
#define CHANNELS 1
#define SAMPLE_SIZE 16
#define SAMPLE_TYPE SignedInt

//开始录音
void MainWindow::on_pushButton_record_clicked()
//void MainWindow::on_record_clicked()
{
    //qDebug() << "Clicked record" << count;
    count ++;
    if(count == 200) {
        count = 0;
    }
    qDebug() << "Clicked record" << count;

    // start to capure
    if (count % 2 == 1) {
        ui->pushButton_record->setText("stop");

#if 0
        QAudioFormat format;
        format.setSampleRate(SAMPLE_RATE);
        format.setChannelCount(CHANNELS);
        //format.setSampleSize(8);
        format.setCodec("audio/wav");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::SignedInt);

        QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
        QString str=info.deviceName();
        qDebug()<<"使用的录音设备是:"<<str<<endl;
        if(!info.isFormatSupported(format))
        {
                format = info.nearestFormat(format);
        }
        input = new QAudioInput(format, this);
#endif

    qDebug() << "Will get the availableDevices";
    const auto &&availableDevices = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
    if(!availableDevices.isEmpty())
    {
        qDebug() << "get the availableDevices not empty";
        foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioInput)) {
                qDebug() << "Device name: " << deviceInfo.deviceName();
                QString curName = deviceInfo.deviceName();
                //QString atvName = QString("ATV");
                QString atvName = QString("Telink");
                //QString atvName = QString("PCH");
                // Contain ATV, then select it
                bool i = curName.contains(atvName);
                if(i) {
                    qDebug() << "Found the device, use it ^^";
                    m_currentDeviceInput = deviceInfo;
                    break;
                }
        }

        qDebug() << "Not Found the device, use Default !!!";
        //if(m_currentDevice == NULL) {
        //        m_currentDevice = availableDevices.first();
        //}

        QAudioFormat format;
#if USE_SAMPLE_16000
        format.setSampleRate(16000);
#else
        format.setSampleRate(8000);
#endif
        format.setSampleRate(SAMPLE_RATE);
        format.setChannelCount(CHANNELS);
        format.setSampleSize(16);
        format.setSampleType(QAudioFormat::SignedInt);
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setCodec("audio/pcm");

        input = new QAudioInput(m_currentDeviceInput, format, this);
    } else {
        qDebug() << "availableDevices is empty";
    }
        file =new QFile();
        file->setFileName(current_path);//设置其实设置音频文件的存放路径(输入音频名及存放路径)
        bool is_open =file->open(QIODevice::WriteOnly | QIODevice::Truncate);
        if(!is_open) {
                qDebug()<<"打开失败"<<endl;
                exit(1);
        }
        //file->write("0x55",44); // Here we fill 0x55 our for reserving place for future header

#if 0
        //print out the device specifications
        foreach(const QAudioDeviceInfo &deviceInfo,     QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
        {
                qDebug() << "\nSuported Input devices";
                qDebug() << "\nDevice name: "             << deviceInfo.deviceName();
                qDebug() << "Supported channel count: "   << deviceInfo.supportedChannelCounts();
                qDebug() << "Supported Codec: "           << deviceInfo.supportedCodecs();
                qDebug() << "Supported byte order: "      << deviceInfo.supportedByteOrders();
                qDebug() << "Supported Sample Rate: "     << deviceInfo.supportedSampleRates();
                qDebug() << "Supported Sample Size: "     << deviceInfo.supportedSampleSizes();
                qDebug() << "Supported Sample Type: "     << deviceInfo.supportedSampleTypes();
                qDebug() << "Preferred Device settings:"  << deviceInfo.preferredFormat();
        }
        foreach(const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput))
        {
                qDebug() << "\nSuported output devices";
                qDebug() << "Device name: "             << deviceInfo.deviceName();
                qDebug() << "Supported channel count: "   << deviceInfo.supportedChannelCounts();
                qDebug() << "Supported Codec: "           << deviceInfo.supportedCodecs();
                qDebug() << "Supported byte order: "      << deviceInfo.supportedByteOrders();
                qDebug() << "Supported Sample Rate: "     << deviceInfo.supportedSampleRates();
                qDebug() << "Supported Sample Size: "     << deviceInfo.supportedSampleSizes();
                qDebug() << "Supported Sample Type: "     << deviceInfo.supportedSampleTypes();
                qDebug() << "Preferred Device settings:"  << deviceInfo.preferredFormat();
        }
#endif
        ui->label->setText("Recording...");
        input->start(file);
        ui->statusBar->showMessage("Recording, click the stop to finish the recording");
    } else{
        ui->pushButton_record->setText("start");
        input->stop();
        //file->seek(0);
        //writeWavHeader(input);
        file->close();
        ui->label->setText("Recording finished, click Play to listen, or Record to make a new recording");
        ui->statusBar->showMessage("File saved");
        ui->lineEdit->setText(current_path);
    }

}

//播放录音
void MainWindow::on_pushButton_play_clicked()
//void MainWindow::on_pushButton_clicked()
{
    countPlay ++;
    if(countPlay == 200) {
        countPlay = 0;
    }
    qDebug() << "Clicked play" << countPlay;

    // start to play
    //if (countPlay % 2 == 1) {
    if(file != NULL){

        file->setFileName(current_path);
        bool exist = file->open(QIODevice::ReadOnly);
        if(!exist) {
            ui->label->setText("Please record first");
            ui->statusBar->showMessage("File not found!");
            //return;
        } else {

#if 0
                QAudioFormat format;
                format.setSampleRate(SAMPLE_RATE);
                format.setChannelCount(CHANNELS);
                //format.setSampleSize(8);
                format.setCodec("audio/wav");
                format.setByteOrder(QAudioFormat::LittleEndian);
                format.setSampleType(QAudioFormat::SignedInt);

                output = new QAudioOutput(format);
#endif
                const auto &&availableDevices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
                if(!availableDevices.isEmpty())
                {
                        foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) {
                                qDebug() << "Device name: " << deviceInfo.deviceName();
                                QString curName = deviceInfo.deviceName();
                                QString atvName = QString("ATV");
                                //QString atvName = QString("PCH");
                                // Contain ATV, then select it
                                bool i = curName.contains(atvName);
                                if(i) {
                                        qDebug() << "Found the device, use it ^^";
                                        m_currentDeviceOutput = deviceInfo;
                                        break;
                                }
                        }

                        qDebug() << "Not Found the device, use Default !!!";
                        //if(m_currentDevice == NULL) {
                        //        m_currentDevice = availableDevices.first();
                        //}
                        //m_currentDeviceOutput = availableDevices.first();

                        QAudioFormat format;
					#if USE_SAMPLE_16000
                        format.setSampleRate(16000);
					#else
                        format.setSampleRate(8000);
					#endif
                        format.setSampleRate(SAMPLE_RATE);
                        format.setChannelCount(CHANNELS);
                        format.setSampleSize(16);
                        format.setSampleType(QAudioFormat::SignedInt);
                        format.setByteOrder(QAudioFormat::LittleEndian);
                        format.setCodec("audio/pcm");

                        output = new QAudioOutput(m_currentDeviceOutput, format, this);
                }
                ui->statusBar->showMessage("Playing...");
                output->start(file);
                ui->statusBar->showMessage("Play Finished");
        }
    }
   // else { // stop the play
   //     output->stop();
   //     file->close();
   //     ui->statusBar->showMessage("Play stopped");
   // }

}

void MainWindow::on_pushButton_clicked()
{
        QFile file(current_path);
        file.remove();
        ui->statusBar->showMessage("File removed");
        ui->lineEdit->setText("");
}
